文件創建後可能要修改標記或是更改上傳的檔案
只能修改自己發的文件
先看使用者是否登入以及要修改的文件是不是屬於此使用者
如果是get進入就從資料庫裡面將文件的資料調出來並設為預設內容
如果文件本身有附件但只是改標題或是remark 則附件延用
如果要上傳新的附件則覆蓋或是創建
doc_info/views.py
@login_required
def doc_modify(request,doc_id):
user = request.user
Doc_warehouse = doc_warehouse.objects.filter(user_id=user.id)
try:
doc = Doc_warehouse.get(id=doc_id)
if request.method == "POST":
user_id = request.user.id
doc_create_date = doc_warehouse.objects.get(id=doc_id).create_date
doc_title = request.POST.get('title','')
doc_remark = request.POST.get('remark','')
upload_file = request.FILES.get('upload_file',doc.upload_file)
doc = doc_warehouse(
id = doc_id,
create_date = doc_create_date,
user_id = user_id,
title = doc_title,
remark = doc_remark,
upload_file = upload_file,
)
doc.save()
return redirect('/doc/user/list')
else:
form = ModifyForm(initial={"title":f"{doc.title}", "remark":f"{doc.remark}"})
context = {
'form': form,
'doc': doc,
}
return render(request, 'doc/modify.html', context)
except Exception as e:
print(e)
return redirect('/doc/user/list')
與create最大不同是需要doc_id
doc_info/urls.py
urlpatterns = [
path('doc/modify/<int:doc_id>', views.doc_modify, name='modify'),
]
自動帶入文件資訊
templates/test.html
{% block content %}
<a href="{% url 'doc_info:main' %}">Main page</a> |
<a href="{% url 'auth_info:profile' %}">My Profile</a> |
<a href="{% url 'account_logout' %}">Logout</a>
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<h3>Modify Document</h3>
<table>
<tr>
<th>Author: </th>
<td>{{ user.first_name }} {{ user.last_name }}</td>
</tr>
<tr>
<th>Contact Email: </th>
<td>{{ user.email }}</td>
</tr>
<tr>
<th>Contact Phone: </th>
<td>{{ user.userprofile.phone_number }}</td>
</tr>
<!-- need to have some gap here -->
<tr>
<th>Title: </th>
<td>{{ form.title }}</td>
</tr>
<tr>
<th>Remark: </th>
<td>{{ form.remark }}</td>
</tr>
<tr>
<th>Attachment: </th>
<td>{{ doc.upload_file }}<input type="file" name="upload_file"></td>
</tr>
</table>
<div class="button-wrapper submit">
<input type="submit" value="Save" />
</div>
</form>
{% endblock %}
modify page畫面